using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using community.Data;

namespace community.Controllers
{
    /// <summary>
    /// 房屋查询参数
    /// </summary>
    public class HouseQueryDTO
    {
        /// <summary>
        /// 楼号
        /// </summary>
        public string? BuildingNo { get; set; }

        /// <summary>
        /// 单元号
        /// </summary>
        public string? UnitNo { get; set; }

        /// <summary>
        /// 房间号
        /// </summary>
        public string? RoomNo { get; set; }

        /// <summary>
        /// 房屋状态（空置/已售/出租等）
        /// </summary>
        public string? Status { get; set; }

        /// <summary>
        /// 业主ID
        /// </summary>
        public int? OwnerId { get; set; }

        /// <summary>
        /// 所属小区ID
        /// </summary>
        public int? ComplexId { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageNumber { get; set; } = 1;
    }

    /// <summary>
    /// 创建/更新房屋的数据模型
    /// </summary>
    public class HouseDTO
    {
        /// <summary>
        /// 楼号
        /// </summary>
        [Required(ErrorMessage = "楼号不能为空")]
        public string BuildingNo { get; set; }

        /// <summary>
        /// 单元号
        /// </summary>
        [Required(ErrorMessage = "单元号不能为空")]
        public string UnitNo { get; set; }

        /// <summary>
        /// 房间号
        /// </summary>
        [Required(ErrorMessage = "房间号不能为空")]
        public string RoomNo { get; set; }

        /// <summary>
        /// 业主ID
        /// </summary>
        public int? OwnerId { get; set; }

        /// <summary>
        /// 房屋状态
        /// </summary>
        [Required(ErrorMessage = "房屋状态不能为空")]
        public string Status { get; set; }

        /// <summary>
        /// 房屋面积（平方米）
        /// </summary>
        [Required(ErrorMessage = "房屋面积不能为空")]
        [Range(1, 1000, ErrorMessage = "房屋面积必须在1-1000平方米之间")]
        public double Area { get; set; }

        /// <summary>
        /// 所属小区ID
        /// </summary>
        [Required(ErrorMessage = "所属小区不能为空")]
        public int ComplexId { get; set; }
    }

    /// <summary>
    /// 房屋状态更新模型
    /// </summary>
    public class HouseStatusDTO
    {
        /// <summary>
        /// 房屋状态
        /// </summary>
        [Required(ErrorMessage = "状态不能为空")]
        public string Status { get; set; }

        /// <summary>
        /// 状态变更说明
        /// </summary>
        public string? Remark { get; set; }
    }

    /// <summary>
    /// 房屋信息管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class HouseController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public HouseController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取房屋列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>房屋列表和总数</returns>
        /// <response code="200">成功获取房屋列表</response>
        /// <response code="400">查询参数验证失败</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> GetHouses([FromQuery] HouseQueryDTO query)
        {
            var houses = _context.Houses
                .Include(h => h.Owner)
                .Include(h => h.Complex)
                    .ThenInclude(c => c.Committee)
                .AsQueryable();

            if (!string.IsNullOrEmpty(query.BuildingNo))
                houses = houses.Where(h => h.BuildingNo.Contains(query.BuildingNo));

            if (!string.IsNullOrEmpty(query.UnitNo))
                houses = houses.Where(h => h.UnitNo.Contains(query.UnitNo));

            if (!string.IsNullOrEmpty(query.RoomNo))
                houses = houses.Where(h => h.RoomNo.Contains(query.RoomNo));

            if (!string.IsNullOrEmpty(query.Status))
                houses = houses.Where(h => h.Status == query.Status);

            if (query.OwnerId.HasValue)
                houses = houses.Where(h => h.OwnerId == query.OwnerId);

            if (query.ComplexId.HasValue)
                houses = houses.Where(h => h.ComplexId == query.ComplexId);

            var total = await houses.CountAsync();

            var pagedHouses = await houses
                .Skip((query.PageNumber - 1) * query.PageSize)
                .Take(query.PageSize)
                .Select(h => new
                {
                    h.Id,
                    h.BuildingNo,
                    h.UnitNo,
                    h.RoomNo,
                    h.Status,
                    h.Area,
                    h.ComplexId,
                    h.CreatedAt,
                    h.UpdatedAt,
                    Owner = h.Owner != null ? new
                    {
                        h.Owner.Id,
                        h.Owner.Name,
                        h.Owner.Phone
                    } : null,
                    Complex = h.Complex != null ? new
                    {
                        h.Complex.Id,
                        h.Complex.Name,
                        h.Complex.Address
                    } : null
                })
                .ToListAsync();

            return Ok(new
            {
                Total = total,
                Items = pagedHouses
            });
        }

        /// <summary>
        /// 获取指定房屋的详细信息
        /// </summary>
        /// <param name="id">房屋ID</param>
        /// <returns>房屋详细信息</returns>
        /// <response code="200">成功获取房屋信息</response>
        /// <response code="404">指定ID的房屋不存在</response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetHouse(int id)
        {
            var house = await _context.Houses
                .Include(h => h.Owner)
                .Include(h => h.Complex)
                    .ThenInclude(c => c.Committee)
                .FirstOrDefaultAsync(h => h.Id == id);

            if (house == null)
                return NotFound();

            return Ok(house);
        }

        /// <summary>
        /// 创建新房屋
        /// </summary>
        /// <param name="dto">房屋信息</param>
        /// <returns>新创建的房屋信息</returns>
        /// <response code="201">成功创建房屋</response>
        /// <response code="400">提供的数据无效</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> CreateHouse(HouseDTO dto)
        {
            // 检查小区是否存在
            var complex = await _context.Complex.FindAsync(dto.ComplexId);
            if (complex == null)
                return BadRequest("指定的小区不存在");

            // 如果指定了业主，检查业主是否存在
            if (dto.OwnerId.HasValue)
            {
                var owner = await _context.Residents.FindAsync(dto.OwnerId);
                if (owner == null)
                    return BadRequest("指定的业主不存在");
            }

            var house = new House
            {
                BuildingNo = dto.BuildingNo,
                UnitNo = dto.UnitNo,
                RoomNo = dto.RoomNo,
                OwnerId = dto.OwnerId,
                Status = dto.Status,
                Area = dto.Area,
                ComplexId = dto.ComplexId,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            _context.Houses.Add(house);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetHouse), new { id = house.Id }, house);
        }

        /// <summary>
        /// 更新房屋信息
        /// </summary>
        /// <param name="id">房屋ID</param>
        /// <param name="dto">更新的房屋信息</param>
        /// <returns>更新后的房屋信息</returns>
        /// <response code="200">成功更新房屋信息</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的房屋不存在</response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateHouse(int id, HouseDTO dto)
        {
            var house = await _context.Houses.FindAsync(id);
            if (house == null)
                return NotFound();

            // 检查小区是否存在
            var complex = await _context.Complex.FindAsync(dto.ComplexId);
            if (complex == null)
                return BadRequest("指定的小区不存在");

            // 如果指定了业主，检查业主是否存在
            if (dto.OwnerId.HasValue)
            {
                var owner = await _context.Residents.FindAsync(dto.OwnerId);
                if (owner == null)
                    return BadRequest("指定的业主不存在");
            }

            house.BuildingNo = dto.BuildingNo;
            house.UnitNo = dto.UnitNo;
            house.RoomNo = dto.RoomNo;
            house.OwnerId = dto.OwnerId;
            house.Status = dto.Status;
            house.Area = dto.Area;
            house.ComplexId = dto.ComplexId;
            house.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(house);
        }

        /// <summary>
        /// 更新房屋状态
        /// </summary>
        /// <param name="id">房屋ID</param>
        /// <param name="dto">状态信息</param>
        /// <returns>更新后的房屋信息</returns>
        /// <response code="200">成功更新状态</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的房屋不存在</response>
        [HttpPatch("{id}/status")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateHouseStatus(int id, HouseStatusDTO dto)
        {
            var house = await _context.Houses.FindAsync(id);
            if (house == null)
                return NotFound();

            house.Status = dto.Status;
            house.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(house);
        }

        /// <summary>
        /// 删除房屋
        /// </summary>
        /// <param name="id">房屋ID</param>
        /// <returns>无内容</returns>
        /// <response code="204">成功删除房屋</response>
        /// <response code="404">指定ID的房屋不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteHouse(int id)
        {
            var house = await _context.Houses.FindAsync(id);
            if (house == null)
                return NotFound();

            _context.Houses.Remove(house);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
} 